﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using ERPForms;
using System.Drawing.Imaging;
using System.Data.SqlClient;
using System.IO;


namespace ResUma
{
    public partial class DocumenteScanateFrm : FrmWorkspace
    {
        ADFScan _scanner;
        int[] _colors = { 1, 2, 4 };
        private Int32 ScanResolution = 300;
        private Int32 HorizontalExtent = 2550;
        private Int32 VerticalExtent = 3500;
        private Int32 ColorFormat = 0;
        private Boolean _Debug = false;

        public DocumenteScanateFrm(ModuleClass mc): base(mc)
        {
            InitializeComponent();
            workConnString = mc.workConnectionString;
            eSRPDataSet.eDocumente.PublicColumn.DefaultValue = false;
            eSRPDataSet.eDocumente.CodColumn.DefaultValue = String.Empty;
            eSRPDataSet.eDocumente.DenumireColumn.DefaultValue = String.Empty;
            eSRPDataSet.eDocumente.CopieColumn.DefaultValue = false;
            
            eDocumenteTableAdapter.Adapter.RowUpdated += new SqlRowUpdatedEventHandler(Adapter_RowUpdated);

            personalDGV.m_AutoCompletionColumns.Add(idPersoanaDataGridViewTextBoxColumn);

            dataDocDTP.Format = DateTimePickerFormat.Custom;
            dataDocDTP.CustomFormat = "dd.MM.yyyy";
            colorOptionsBindingSource.Add(new ColorOptions("Fara", 0));
            colorOptionsBindingSource.Add(new ColorOptions("Color", 1));
            colorOptionsBindingSource.Add(new ColorOptions("Nuante de gri", 2));
            colorOptionsBindingSource.Add(new ColorOptions("Text", 4));
            colorOptionsBindingSource.Add(new ColorOptions("Masca", 16)); 
        }

        void Adapter_RowUpdated(object sender, SqlRowUpdatedEventArgs e)
        {
            if (e.Errors != null)
                throw e.Errors;
            if (e.StatementType == StatementType.Insert)
            {
                foreach (DataRow row in 
                    eSRPDataSet.eDocumentPage.Select("IDDocument=" + e.Row["IDDocument", DataRowVersion.Original].ToString(),
                        "IDDocument", DataViewRowState.Added))
                {
                    row["IDDocument"] = e.Row["IDDocument"];
                }

                foreach (DataRow row in
                    eSRPDataSet.eDocumentPersoana.Select("IDDocument=" + e.Row["IDDocument", DataRowVersion.Original].ToString(),
                        "IDDocument", DataViewRowState.Added))
                {
                    row["IDDocument"] = e.Row["IDDocument"];
                }



            }
        }

        private void DocumenteScanateFrm_Load(object sender, EventArgs e)
        {
            try
            {
                SqlConnection sqlCon = DeschideConexiune(workConnString);
                this.persoaneTableAdapter.Connection = sqlCon;
                this.persoaneTableAdapter.Fill(this.eSRPDataSet.Persoane);
                this.eDocumentPersoanaTableAdapter.Connection = sqlCon;
                this.eDocumentPersoanaTableAdapter.Fill(this.eSRPDataSet.eDocumentPersoana);
                this.eDocumentTipTableAdapter.Connection = sqlCon;
                this.eDocumentTipTableAdapter.Fill(this.eSRPDataSet.eDocumentTip);
                //this.eDocumentPageTableAdapter.Connection = sqlCon;
                //this.eDocumentPageTableAdapter.Fill(this.eSRPDataSet.eDocumentPage);
                this.eDocumenteTableAdapter.Connection = sqlCon;
                this.eDocumenteTableAdapter.Fill(this.eSRPDataSet.eDocumente);

                Object ret = GetSetupValue("ResUmaSetup", "ScanRes", ModuleInfo.CodUnitate, sqlCon);
                ScanResolution = Convert.ToInt32(ret);
                ret = GetSetupValue("ResUmaSetup", "OrizExtent", ModuleInfo.CodUnitate, sqlCon);
                HorizontalExtent = Convert.ToInt32(ret);
                ret = GetSetupValue("ResUmaSetup", "VertExtent", ModuleInfo.CodUnitate, sqlCon);
                VerticalExtent = Convert.ToInt32(ret);
                ret = GetSetupValue("ResUmaSetup", "ColorFormat", ModuleInfo.CodUnitate, sqlCon);
                ColorFormat = Convert.ToInt32(ret);
                ret = GetSetupValue("ResUmaSetup", "ScanDebug", ModuleInfo.CodUnitate, sqlCon);
                _Debug = Convert.ToBoolean(ret);
                colorFormatComboBox.SelectedValue = ColorFormat;
                InchideConexiune(sqlCon);
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
                return;
            }


            AddBindingSource(eDocumenteBindingSource);
            AddTableAdaptor(eDocumenteTableAdapter.Adapter);

            AddBindingSource(fKeDocumentPageeDocumenteBindingSource);
            AddTableAdaptor(eDocumentPageTableAdapter.Adapter);
            AddBindingSource(eDocumentPersoanaBindingSource);
            AddTableAdaptor(eDocumentPersoanaTableAdapter.Adapter);


            if (eDocumenteBindingSource.Count == 0)
                eDocumenteBindingSource.AddNew();

            //if (eDocumentPersoanaBindingSource.Count == 0)
            //    eDocumentPersoanaBindingSource.AddNew();

            AddButton("Scaneaza", global::ResUma.Properties.Resources.scanner, Scaneaza, ToolStripItemAlignment.Right, true);

            
        }

        private void Scaneaza(object sender, EventArgs e)
        {
            _scanner = new ADFScan();
            _scanner.Scanning += new EventHandler<WiaImageEventArgs>(_scanner_Scanning);
            _scanner.ScanComplete += new EventHandler(_scanner_ScanComplete);
            _scanner.BeginScan((ScanColor)colorFormatComboBox.SelectedValue, ScanResolution, HorizontalExtent, VerticalExtent, _Debug);
        }

        void _scanner_ScanComplete(object sender, EventArgs e)
        {
            MessageBox.Show("Scanare Completa");
        }


        void _scanner_Scanning(object sender, WiaImageEventArgs e)
        {
            if(eDocumenteBindingSource.Current==null)
                return;
            ESRPDataSet.eDocumenteRow dRow = ((DataRowView)eDocumenteBindingSource.Current).Row as ESRPDataSet.eDocumenteRow;
            short pagNr = (short)(fKeDocumentPageeDocumenteBindingSource.Count+1);
            string filename = "C:\\temp\\"/*textBox1.Text*/ + "image" + pagNr.ToString() + ".jpg";
            //listBox1.Items.Add(filename);

            fKeDocumentPageeDocumenteBindingSource.AddNew();
            ESRPDataSet.eDocumentPageRow ePag = ((DataRowView)fKeDocumentPageeDocumenteBindingSource.Current).Row as ESRPDataSet.eDocumentPageRow;
      
            

            ePag.NrPagina = pagNr;
            ePag.Titlu = "Titlu";
            ePag.Descriere = "Pagina " + pagNr.ToString() + " scanata la " + DateTime.Now.ToLongDateString() + " ora " + DateTime.Now.ToLongTimeString();
            ePag.IDDocument = dRow.IDDocument;
            MemoryStream ms = new MemoryStream();
            e.ScannedImage.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);

            ePag.Data = DateTime.Now;
            ePag.Continut = ms.GetBuffer();
            //ePag.EndEdit(); 
            fKeDocumentPageeDocumenteBindingSource.EndEdit();
            ///actualizare 
            pictureBox1.Image = Image.FromStream(ms);


            //e.ScannedImage.Save(filename, ImageFormat.Jpeg);//FILES ARE RETURNED AS BITMAPS
            
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            if (paginiDGV.SelectedRows.Count == 0)
                return;
            ESRPDataSet.eDocumentPageRow pRow = ((DataRowView)paginiDGV.SelectedRows[0].DataBoundItem).Row as ESRPDataSet.eDocumentPageRow;
            if (pRow.RowState!= System.Data.DataRowState.Detached &&    pRow.Continut != null )
            {
                MemoryStream ms = new MemoryStream(pRow.Continut);
                pictureBox1.Image = Image.FromStream(ms);
            }
        }

        private void eDocumenteBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            if (eDocumenteBindingSource.Current == null)
                return;
            ESRPDataSet.eDocumenteRow ePag = ((DataRowView)eDocumenteBindingSource.Current).Row as ESRPDataSet.eDocumenteRow;
            this.eDocumentPageTableAdapter.Connection = DeschideConexiune(workConnString);
            this.eDocumentPageTableAdapter.FillByDocument(this.eSRPDataSet.eDocumentPage,ePag.IDDocument);
            InchideConexiune(this.eDocumentPageTableAdapter.Connection);

            //if (eDocumentPersoanaBindingSource.Count == 0 && eDocumentPersoanaBindingSource.AllowNew)
            //    eDocumentPersoanaBindingSource.AddNew();
        }

        override public void Salvare(object sender, EventArgs args)
        {
            if (eDocumentPersoanaBindingSource.Count==0)
            {
                TrateazaExceptie(new Exception("Va rugam sa asignati documentul dosarului cel putin unei persoane!"), eDocumentPersoanaBindingSource);
                return;
            }

            if (fKeDocumentPageeDocumenteBindingSource.Count == 0)
            {
                TrateazaExceptie(new Exception("Va rugam sa scanati cel putin o pagina pentru document!"), eDocumentPersoanaBindingSource);
                return;
            }

            this.SuspendLayout();
            base.Salvare(this, args);
            ResumeLayout();


            if (EroareSalvare)
                return;

        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (fKeDocumentPageeDocumenteBindingSource.Current == null)
                return;
            ESRPDataSet.eDocumentPageRow ePag = ((DataRowView)fKeDocumentPageeDocumenteBindingSource.Current).Row as ESRPDataSet.eDocumentPageRow;
            MemoryStream ms = new MemoryStream(ePag.Continut);
            Image img = Image.FromStream(ms);
            img.RotateFlip(RotateFlipType.Rotate90FlipNone);
            pictureBox1.Image = img;
            MemoryStream ms2 = new MemoryStream();
            img.Save(ms2, System.Drawing.Imaging.ImageFormat.Gif);

            ePag.Continut =ms2.GetBuffer();
            fKeDocumentPageeDocumenteBindingSource.EndEdit();

        }
        
    }
}
